<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车 - 运动商城</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/style.css">
    <!-- 确保jQuery在Bootstrap之前加载 -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <!-- 导航栏 -->
    <jsp:include page="common/header.jsp"/>
    
    <!-- 购物车内容 -->
    <div class="container py-5">
        <h2 class="mb-4">我的购物车</h2>
        
        <c:choose>
            <c:when test="${empty cartList}">
                <div class="text-center py-5">
                    <img src="${pageContext.request.contextPath}/static/images/empty-cart.png" alt="空购物车" class="mb-3" style="max-width: 200px;">
                    <h4 class="mb-3">您的购物车还是空的</h4>
                    <p class="text-muted mb-4">快去添加喜欢的商品吧！</p>
                    <a href="${pageContext.request.contextPath}/" class="btn btn-primary">去购物</a>
                </div>
            </c:when>
            <c:otherwise>
                <div class="card">
                    <div class="card-header bg-white">
                        <div class="row align-items-center">
                            <div class="col-1">
                                <div class="form-check">
                                    <input type="checkbox" class="form-check-input" id="select-all">
                                    <label class="form-check-label" for="select-all">全选</label>
                                </div>
                            </div>
                            <div class="col-4">商品信息</div>
                            <div class="col-2 text-center">单价</div>
                            <div class="col-2 text-center">数量</div>
                            <div class="col-2 text-center">小计</div>
                            <div class="col-1 text-center">操作</div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <c:forEach items="${cartList}" var="item">
                            <div class="cart-item p-3 border-bottom" data-id="${item.id}">
                                <div class="row align-items-center">
                                    <div class="col-1">
                                        <div class="form-check">
                                            <input type="checkbox" class="form-check-input item-checkbox" 
                                                   id="item-${item.id}" 
                                                   data-id="${item.id}" 
                                                   ${item.checked == 1 ? 'checked' : ''}>
                                            <label class="form-check-label" for="item-${item.id}"></label>
                                        </div>
                                    </div>
                                    <div class="col-4">
                                        <div class="d-flex">
                                            <div class="cart-item-img me-3">
                                                <a href="${pageContext.request.contextPath}/product/detail/${item.productId}">
                                                    <img src="${not empty item.productImage ? item.productImage : pageContext.request.contextPath.concat('/static/images/product-default.jpg')}" 
                                                         class="img-thumbnail" alt="${item.productName}" style="width: 80px;">
                                                </a>
                                            </div>
                                            <div class="cart-item-info">
                                                <h5 class="mb-1">
                                                    <a href="${pageContext.request.contextPath}/product/detail/${item.productId}" class="text-dark">
                                                        ${item.productName}
                                                    </a>
                                                </h5>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-2 text-center">
                                        <span class="text-danger">¥${item.productPrice}</span>
                                    </div>
                                    <div class="col-2 text-center">
                                        <div class="input-group input-group-sm quantity-control mx-auto" style="width: 120px;">
                                            <button class="btn btn-outline-secondary quantity-minus" type="button" data-id="${item.id}">-</button>
                                            <input type="number" class="form-control text-center quantity-input" 
                                                   value="${item.quantity}" min="1" max="99" 
                                                   data-id="${item.id}" data-price="${item.productPrice}">
                                            <button class="btn btn-outline-secondary quantity-plus" type="button" data-id="${item.id}">+</button>
                                        </div>
                                    </div>
                                    <div class="col-2 text-center">
                                        <span class="text-danger item-total">¥${item.productPrice * item.quantity}</span>
                                    </div>
                                    <div class="col-1 text-center">
                                        <button class="btn btn-sm btn-outline-danger delete-item" type="button" data-id="${item.id}">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </c:forEach>
                    </div>
                    <div class="card-footer bg-white">
                        <div class="row align-items-center">
                            <div class="col-md-6">
                                <button class="btn btn-outline-danger me-2" id="delete-selected" type="button">删除选中商品</button>
                                <button class="btn btn-outline-secondary" id="clear-cart" type="button">清空购物车</button>
                            </div>
                            <div class="col-md-6 text-end">
                                <div class="d-inline-block me-4">
                                    已选商品 <span class="selected-count">0</span> 件
                                </div>
                                <div class="d-inline-block me-4">
                                    合计: <span class="text-danger h4 mb-0" id="total-price">¥${totalPrice}</span>
                                </div>
                                <button class="btn" id="checkout-btn" type="button">
                                    <i class="fas fa-shopping-cart me-1"></i> 去结算(<span class="selected-count">0</span>)
                                </button>
                                <div class="row mt-3">
                                    <div class="col-md-6">
                                        <a href="${pageContext.request.contextPath}/" class="btn btn-outline-primary">
                                            <i class="fas fa-arrow-left me-1"></i> 继续购物
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 底部推荐商品 -->
                <div class="mt-5">
                    <h4 class="mb-3">猜你喜欢</h4>
                    <div class="row">
                        <c:forEach items="${recommendProducts}" var="product" begin="0" end="3">
                            <div class="col-md-3 mb-4">
                                <div class="card h-100">
                                    <a href="${pageContext.request.contextPath}/product/detail/${product.id}">
                                        <img src="${not empty product.mainImage ? product.mainImage : pageContext.request.contextPath.concat('/static/images/product-default.jpg')}" 
                                             class="card-img-top" alt="${product.name}">
                                    </a>
                                    <div class="card-body">
                                        <h5 class="card-title">
                                            <a href="${pageContext.request.contextPath}/product/detail/${product.id}" class="text-dark">${product.name}</a>
                                        </h5>
                                        <p class="card-text text-danger">¥${product.price}</p>
                                        <button class="btn add-to-cart" type="button" data-id="${product.id}">
                                            <i class="fas fa-shopping-cart me-2"></i>加入购物车
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </c:forEach>
                    </div>
                </div>
            </c:otherwise>
        </c:choose>
    </div>
    
    <!-- 页脚 -->
    <jsp:include page="common/footer.jsp"/>
    
    <script>
    $(document).ready(function() {
        // 更新选中商品数量和总价
        function updateSelectedInfo() {
            var selectedCount = $('.item-checkbox:checked').length;
            $('.selected-count').text(selectedCount);
            
            // 计算总价
            var totalPrice = 0;
            $('.item-checkbox:checked').each(function() {
                var itemId = $(this).data('id');
                var price = parseFloat($('.quantity-input[data-id="' + itemId + '"]').data('price'));
                var quantity = parseInt($('.quantity-input[data-id="' + itemId + '"]').val());
                totalPrice += price * quantity;
            });
            
            $('#total-price').text('¥' + totalPrice.toFixed(2));
        }
        
        // 初始化时计算一次
        updateSelectedInfo();
        
        // 全选/取消全选
        $('#select-all').on('change', function() {
            var isChecked = $(this).prop('checked');
            $('.item-checkbox').prop('checked', isChecked);
            
            // 更新所有购物车项的选中状态
            $.ajax({
                url: '${pageContext.request.contextPath}/cart/select-all',
                type: 'POST',
                data: {
                    checked: isChecked ? 1 : 0
                },
                success: function(response) {
                    if (!response.success) {
                        alert(response.message);
                    }
                    updateSelectedInfo();
                }
            });
        });
        
        // 单个商品选中/取消选中
        $('.item-checkbox').on('change', function() {
            var isChecked = $(this).prop('checked');
            var itemId = $(this).data('id');
            
            // 更新购物车项的选中状态
            $.ajax({
                url: '${pageContext.request.contextPath}/cart/select',
                type: 'POST',
                data: {
                    id: itemId,
                    checked: isChecked ? 1 : 0
                },
                success: function(response) {
                    if (!response.success) {
                        alert(response.message);
                    }
                    // 检查是否全部选中
                    var allChecked = $('.item-checkbox:checked').length === $('.item-checkbox').length;
                    $('#select-all').prop('checked', allChecked);
                    updateSelectedInfo();
                }
            });
        });
        
        // 减少数量
        $(document).on('click', '.quantity-minus', function() {
            var input = $(this).closest('.quantity-control').find('.quantity-input');
            var currentValue = parseInt(input.val());
            if (currentValue > 1) {
                input.val(currentValue - 1);
                updateQuantity(input);
            }
        });
        
        // 增加数量
        $(document).on('click', '.quantity-plus', function() {
            var input = $(this).closest('.quantity-control').find('.quantity-input');
            var currentValue = parseInt(input.val());
            var max = parseInt(input.attr('max'));
            if (currentValue < max) {
                input.val(currentValue + 1);
                updateQuantity(input);
            }
        });
        
        // 手动输入数量
        $(document).on('change', '.quantity-input', function() {
            updateQuantity($(this));
        });
        
        // 更新商品数量
        function updateQuantity(input) {
            var itemId = input.data('id');
            var quantity = parseInt(input.val());
            var price = parseFloat(input.data('price'));
            
            // 更新小计
            var totalPrice = (price * quantity).toFixed(2);
            input.closest('.row').find('.item-total').text('¥' + totalPrice);
            
            // 更新购物车数量
            $.ajax({
                url: '${pageContext.request.contextPath}/cart/update',
                type: 'POST',
                data: {
                    id: itemId,
                    quantity: quantity
                },
                success: function(response) {
                    if (!response.success) {
                        alert(response.message);
                        // 如果失败，恢复原来的数量
                        window.location.reload();
                    } else {
                        updateSelectedInfo();
                    }
                }
            });
        }
        
        // 删除单个商品
        $(document).on('click', '.delete-item', function() {
            if (confirm('确定要删除该商品吗？')) {
                var itemId = $(this).data('id');
                
                $.ajax({
                    url: '${pageContext.request.contextPath}/cart/delete',
                    type: 'POST',
                    data: {
                        id: itemId
                    },
                    success: function(response) {
                        if (response.success) {
                            // 删除成功，移除商品项
                            $('.cart-item[data-id="' + itemId + '"]').remove();
                            
                            // 如果购物车为空，刷新页面
                            if ($('.cart-item').length === 0) {
                                window.location.reload();
                            } else {
                                updateSelectedInfo();
                            }
                        } else {
                            alert(response.message);
                        }
                    }
                });
            }
        });
        
        // 删除选中商品
        $('#delete-selected').on('click', function() {
            var selectedItems = $('.item-checkbox:checked');
            
            if (selectedItems.length === 0) {
                alert('请先选择要删除的商品');
                return;
            }
            
            if (confirm('确定要删除选中的商品吗？')) {
                var deletePromises = [];
                
                selectedItems.each(function() {
                    var itemId = $(this).data('id');
                    
                    var promise = $.ajax({
                        url: '${pageContext.request.contextPath}/cart/delete',
                        type: 'POST',
                        data: {
                            id: itemId
                        }
                    });
                    
                    deletePromises.push(promise);
                });
                
                // 等待所有删除请求完成
                $.when.apply($, deletePromises).then(function() {
                    // 刷新页面
                    window.location.reload();
                });
            }
        });
        
        // 清空购物车
        $('#clear-cart').on('click', function() {
            if (confirm('确定要清空购物车吗？')) {
                var deletePromises = [];
                
                $('.cart-item').each(function() {
                    var itemId = $(this).data('id');
                    
                    var promise = $.ajax({
                        url: '${pageContext.request.contextPath}/cart/delete',
                        type: 'POST',
                        data: {
                            id: itemId
                        }
                    });
                    
                    deletePromises.push(promise);
                });
                
                // 等待所有删除请求完成
                $.when.apply($, deletePromises).then(function() {
                    // 刷新页面
                    window.location.reload();
                });
            }
        });

        // 结算按钮点击事件
        $('#checkout-btn').on('click', function() {
            console.log('结算按钮被点击');
            
            // 检查是否有选中的商品
            var selectedCount = $('.item-checkbox:checked').length;
            if (selectedCount === 0) {
                alert('请选择要结算的商品');
                return;
            }
            
            // 获取选中的商品ID列表
            var selectedItems = [];
            $('.item-checkbox:checked').each(function() {
                selectedItems.push($(this).data('id'));
            });
            
            // 发送POST请求到checkout
            $.ajax({
                url: '${pageContext.request.contextPath}/checkout',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    cartItems: selectedItems
                }),
                success: function(response) {
                    if (response.success) {
                        window.location.href = '${pageContext.request.contextPath}/order/detail/' + response.orderNo;
                    } else {
                        if (response.redirect) {
                            window.location.href = response.redirect;
                        } else {
                            alert(response.message || '结算失败，请重试');
                        }
                    }
                },
                error: function(xhr, status, error) {
                    console.error('结算请求失败:', error);
                    alert('结算失败，请重试');
                }
            });
        });
        
        // 添加推荐商品到购物车
        $('.add-to-cart').on('click', function() {
            var productId = $(this).data('id');
            
            $.ajax({
                url: '${pageContext.request.contextPath}/cart/add',
                type: 'POST',
                data: {
                    productId: productId,
                    quantity: 1
                },
                success: function(response) {
                    if (response.success) {
                        alert('已成功加入购物车');
                        // 刷新页面
                        window.location.reload();
                    } else {
                        alert(response.message || '加入购物车失败');
                    }
                },
                error: function() {
                    alert('加入购物车失败，请稍后再试');
                }
            });
        });
    });
    </script>
</body>
</html> 